import { createRouter, createWebHistory } from "vue-router";
//- 异步加载组件
import { defineAsyncComponent } from "vue";
//- 路由规则
const myRouter = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "Login",
    component: defineAsyncComponent(() => import("../views/login/Login.vue")),
  },
  {
    path: "/home",
    name: "Home",
    component: defineAsyncComponent(() => import("../views/home/Home.vue")),
  },
];
//- 创建路由对象
const router = createRouter({
  history: createWebHistory(),
  routes: myRouter,
});
//全局守卫  访问非Login界面时，验证是否已登录
router.beforeEach((to, from, next) => {
  //判断是否已登录 查sessionStorage中是否有authorization信息
  let authorization = sessionStorage.getItem("Authorization");
  //判断路由的别名不是登录且未进行登录认证，就跳转去登录
  if (to.name != "Login" && !authorization) {
    next({ name: "Login" });
  } else if (to.name == "Login" && authorization) {
    //已登录，不允许退回到登录页面
    next({ name: "Home" });
  } else {
    next();
  }
});
//-将路由暴露出去，其他文件才能访问
export default router;
